/**
 * Copyright (C), 2015-2020, XXX有限公司
 * FileName: FanweUserRegisterController
 * Author:   Administrator
 * Date:     2020/11/17 12:14
 * Description: aa
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package io.renren.modules.live.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.form.RegisterForm;
import io.renren.modules.live.entity.FanweAnchorEntity;
import io.renren.modules.live.entity.FanweUserEntity;
import io.renren.modules.live.service.FanweAnchorService;
import io.renren.modules.live.service.FanweAnchorTokenService;
import io.renren.modules.live.service.FanweUserService;
import io.renren.modules.live.service.FanweUserTokenService;
import io.renren.modules.live.vo.UserLoginVo;
import io.renren.modules.sys.service.SysUserTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 〈一句话功能简述〉<br> 
 * 〈aa〉
 *
 * @author Administrator
 * @create 2020/11/17
 * @since 1.0.0
 */
@RestController
@RequestMapping("/web")
@Api(tags = "登录注册接口")
public class FanweUserRegisterController {

    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Autowired
    private FanweUserService fanweUserService;

    @Autowired
    private FanweUserTokenService fanweUserTokenService;

    @Autowired
    private FanweAnchorService fanweAnchorService;

    @Autowired
    private FanweAnchorTokenService fanweAnchorTokenService;


    /**
     * 普通用户注册
     * @param userLoginVo
     * @return
     */
    @PostMapping("/usr/registry")
    @ApiOperation("普通用户注册")
    public R register(@RequestBody @ApiParam(value = "接受用户信息") UserLoginVo userLoginVo){
        //手机号格式判断
//        String phone = userLoginVo.getNickNumber();
//        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
//        if (Pattern.matches(regex, phone)) {
//            System.out.println("校验成功");
//        } else {
//            return R.error("请正确输入手机号");
//        }
        if(userLoginVo.getNickNumber() == null){
            return R.error("账号不能为空");
        }
        if( userLoginVo.getNickNumber().length()<=6){
            return R.error("账号长度不能小于6");
        }
        //根据用户名数据库查询是否存在
        FanweUserEntity userEntity = fanweUserService.queryByUserName(userLoginVo.getNickNumber());
        if(userEntity!=null){
           return R.error("该手机号已经注册,请直接登录");
        }
        //保存到数据库
        FanweUserEntity fanweUserEntity = new FanweUserEntity();
        fanweUserEntity.setId(IdWorker.getId());
        fanweUserEntity.setNickNumber(userLoginVo.getNickNumber());
        fanweUserEntity.setPhone(userLoginVo.getNickNumber());
        fanweUserEntity.setPaypassword(DigestUtils.sha256Hex("0000"));
        fanweUserEntity.setHeadImage("http://101.200.45.250/group1/M00/00/00/Zcgt-l-8zleABvbKAAGQtaRWibM152.png");
        fanweUserEntity.setUserPwd(DigestUtils.sha256Hex(userLoginVo.getUserPwd()));
        fanweUserEntity.setCreateTime(new Date());
        fanweUserEntity.setUserType(2);
        fanweUserEntity.setStatus(1);
        fanweUserService.save(fanweUserEntity);
        return R.ok("注册成功");
    }

    /**
     * 普通||主播  用户登录
     * @param
     * @return
     */
    @PostMapping("/usr/login")
    @ApiOperation("登录")
    public R login(@RequestBody UserLoginVo userLoginVo){
        if(userLoginVo.getUserPwd()!=null&&userLoginVo.getUserPwd()!=""){
            //手机号格式判断
//            String phone = userLoginVo.getNickNumber();
//            String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
//            if (Pattern.matches(regex, phone)) {
//                System.out.println("校验成功");
//            } else {
//                return R.error("请正确输入手机号");
//            }

            //用户登录  (普通用户正常登录  ,主播登录要求输入 推广码)
            if(StringUtils.isEmpty(userLoginVo.getCode())){
                //推广码为空  为普通用户 登录
                FanweUserEntity userEntity = fanweUserService.queryByUserName(userLoginVo.getNickNumber());
                //账号不存在、密码错误
                if(userEntity == null || !userEntity.getUserPwd().equals(new Sha256Hash(userLoginVo.getUserPwd(), userEntity.getSalt()).toHex())) {
                    return R.error("账号或密码不正确");
                }
                //账号锁定
                if(userEntity.getStatus() == 0){
                    return R.error("账号已被锁定,请联系管理员");
                }
                //生成token，并保存到数据库
                R r = fanweUserTokenService.createToken(userEntity.getId());
                return r;
            } else {
                //主播登录
                FanweAnchorEntity anchorEntity = fanweAnchorService.queryByUserName(userLoginVo.getNickNumber());
                //账号不存在、密码错误
                if(anchorEntity == null || !anchorEntity.getUserPwd().equals(new Sha256Hash(userLoginVo.getUserPwd(), anchorEntity.getSalt()).toHex())) {
                    return R.error("账号或密码不正确");
                }
                //账号锁定
                if(anchorEntity.getStatus() == 0){
                    return R.error("账号已被锁定,请联系管理员");
                }
                //账号锁定
                if(!userLoginVo.getCode().equals(anchorEntity.getCode())){
                    return R.error("邀请码不正确,请联系管理员或重新输入");
                }
                //生成token，并保存到数据库
                R r = fanweAnchorTokenService.createToken(anchorEntity.getAnchorId());
                return r;
            }
        }else {
            return R.error("请输入用户或密码");
        }


    }
    /**
     * 退出
     */
    @ApiOperation("退出")
    @PostMapping("/usr/logout")
    public R logout(@ApiParam(value = "用户ID",required = true) Long userId,
                    HttpServletRequest request) {
        String token = request.getHeader("token");
        String s = token.substring(0, 3);
        if(s.equals("sys")){
            sysUserTokenService.logout(userId);

        }else if(s.equals("usr")){
            fanweUserTokenService.logout(userId);

        }else if(s.equals("anc")){
            fanweAnchorTokenService.logout(userId);
        }
        return R.ok("退出成功");
    }
}